package com.zf.shuashua.manager;


import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Build;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.WebView;

import com.aliyun.apsara.alivclittlevideo.sts.OnStsResultListener;
import com.aliyun.apsara.alivclittlevideo.sts.StsInfoManager;
import com.aliyun.common.httpfinal.QupaiHttpFinal;
import com.aliyun.downloader.DownloaderManager;
import com.aliyun.private_service.PrivateService;
import com.aliyun.svideo.base.sts.StsInfo;
import com.aliyun.svideo.base.sts.StsInfoService;
import com.aliyun.svideo.base.sts.StsTokenInfo;
import com.aliyun.sys.AlivcSdkCore;
import com.dhcw.sdk.manager.BDAdvanceConfig;
import com.dhcw.sdk.manager.BDManager;
import com.duoyou.task.openapi.DyAdApi;
import com.dydroid.ads.c.ADLoader;
import com.dydroid.ads.c.AdClientConfig;
import com.huawei.openalliance.ad.inter.HiAd;
import com.kk.taurus.playerbase.config.PlayerConfig;
import com.kk.taurus.playerbase.config.PlayerLibrary;
import com.mediamain.android.view.base.FoxSDK;
import com.meis.base.mei.utils.AppUtils;
import com.miui.zeus.mimo.sdk.MimoSdk;
import com.qq.e.ads.cfg.MultiProcessFlag;
import com.qq.e.comm.managers.GDTADManager;
import com.qq.e.comm.managers.setting.GlobalSetting;
import com.tencent.bugly.Bugly;
import com.tencent.bugly.beta.Beta;
import com.vise.log.ViseLog;
import com.vise.log.inner.LogcatTree;
import com.vise.xsnow.http.ViseHttp;
import com.vise.xsnow.http.callback.ACallback;
import com.vise.xsnow.http.interceptor.HttpLogInterceptor;
import com.zf.shuashua.BuildConfig;
import com.zf.shuashua.R;
import com.zf.shuashua.ShuaApplication;
import com.zf.shuashua.advert.TTAdManagerHolder;
import com.zf.shuashua.api.Constants;
import com.zf.shuashua.api.HttpData;
import com.zf.shuashua.api.MyHttpInterceptor;
import com.zf.shuashua.api.Store;
import com.zf.shuashua.bean.BaseData;
import com.zf.shuashua.helper.UmengHelper;
import com.zf.shuashua.ui.mine.LogUtil;
import com.zf.shuashua.utils.Util;
import com.zf.shuashua.utils.oaid_tool.helpers.DevicesIDsHelper;

import java.net.Proxy;
import java.util.HashMap;
import java.util.Map;

import cn.admobiletop.adsuyi.ADSuyiSdk;
import cn.admobiletop.adsuyi.config.ADSuyiInitConfig;
import io.reactivex.Observable;
import io.reactivex.schedulers.Schedulers;

/**
 * 长豆初始化相关
 */
public class ShunInitialManager {

    private static ShunInitialManager instance;

    private ShunInitialManager() {

    }

    public static ShunInitialManager getInstance() {
        if (null == instance) {
            synchronized (ShunInitialManager.class) {
                if (null == instance) {
                    instance = new ShunInitialManager();
                }
            }
        }
        return instance;
    }

    public void initCommon(Context context) {
        initLog();
        LogUtil.init(BuildConfig.ENABLE_DEBUG);
        initHttp(context);
        QupaiHttpFinal.getInstance().initOkHttpFinal();
        initDownLoader(context);

        Beta.upgradeDialogLayoutId = R.layout.activity_upgrade;
        Beta.dialogFullScreen = false;
        Beta.autoCheckUpgrade = false;
        Bugly.init(context.getApplicationContext(), "700542f4e2", BuildConfig.ENABLE_DEBUG);
        ShuaApplication.androidId = AppUtils.getAndroidID(context);
//        //短视频sdk，暂时只支持api 18以上的版本
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            AlivcSdkCore.register(context.getApplicationContext());
            AlivcSdkCore.setLogLevel(AlivcSdkCore.AlivcLogLevel.AlivcLogDebug);
        }

        UmengHelper.getInstance().init();//初始化友盟
        //优量汇广告SDK初始化
        config(context);
        // 初始化穿山甲广告
        TTAdManagerHolder.init(context);

        Bugly.setAppChannel(context, ShuaApplication.channel);
        // 旺翔
        ADLoader.init(context, new AdClientConfig.Builder().build());
        //推啊
        FoxSDK.init(ShuaApplication.context,"LStcTsHrCoiyj7ejw5KnvpQyq9b","3XZRoz1CuAAbnoV6BFAu5ZyNYVSB21s4vJuCBHG");
        //华为
        HiAd.getInstance(context).initLog(false, Log.ERROR); // 初始化日志
        //多游
        initDy(context);
        //变现猫
        BDAdvanceConfig.getInstance().setAppName("长豆短视频").setDebug(true).enableAudit(false);
        BDManager.getStance().init(context, "14b9d02bb3c043d899040312c06a746d");

        //初始化adMobile
        initADSuyi(context);

        MimoSdk.init(context);
        Beta.enableNotification = false;

        //playerBase播放器
        PlayerLibrary.init(context);
        PlayerConfig.playRecord(false);

        observeOaid(context);

        initStsManager();
    }

    private void initLog() {
        ViseLog.getLogConfig()
                .configAllowLog(BuildConfig.ENABLE_DEBUG)//是否输出日志
                .configShowBorders(BuildConfig.ENABLE_DEBUG)//是否排版显示
                .configTagPrefix("changdoulog");
        ViseLog.setTag("changdou");
        ViseLog.plant(new LogcatTree());//添加打印日志信息到Logcat的树
    }

    private void initDownLoader(Context context) {
        String filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/shua/encryptedApp.dat";
        PrivateService.initService(context, filePath);
        DownloaderManager.getInstance().init(context);
        //TODO：暂时没有拍摄模块，先注释
        // 拷贝assets文件到缓存路径
//        RecordCommon.copyRace(this);
    }

    private void initHttp(Context context) {
        ViseHttp.init(context);
        final Map<String, String> headers = new HashMap<>();
        headers.put("version", Util.getAppVersionName(context));
        //headers.put("sn", Util.getDeviceId(this));
        headers.put("type", Util.getSystemModel());
        headers.put("User-Agent", Util.getUserAgent(context));

        ViseHttp.CONFIG()
                //配置请求主机地址
                .baseUrl(Constants.getBaseUrl())
                .globalHeaders(headers)
                .interceptor(new MyHttpInterceptor())
                //配置日志拦截器
                .interceptor(new HttpLogInterceptor()
                        .setLevel(HttpLogInterceptor.Level.BODY));

        if(!Store.getInstance().isProxy()){
            ViseHttp.CONFIG().proxy(Proxy.NO_PROXY);
        }

        ViseHttp.CONFIG()
                .writeTimeout(20);
        ViseHttp.CONFIG().readTimeout(20);
        ViseHttp.CONFIG().retryCount(1);
    }

    private void initStsManager() {
        StsInfoManager stsInfoManager = StsInfoManager.getInstance();
        stsInfoManager.init(this::getStsInfo);

        //TODO：暂时没有开启sts
        //初始化sts信息
        //getStsInfo(null);
    }

    private void getStsInfo(OnStsResultListener stsResultListener) {
        HttpData.getInstance().postStsInfo(new ACallback<BaseData<StsInfo>>() {
            @Override
            public void onSuccess(BaseData<StsInfo> data) {
                if (data.getCode() == 200 && data.getData() != null) {
                    StsTokenInfo stsTokenInfo = new StsTokenInfo();
                    stsTokenInfo.setSecurityToken(data.getData().SecurityToken);
                    stsTokenInfo.setAccessKeyId(data.getData().AccessKeyId);
                    stsTokenInfo.setAccessKeySecret(data.getData().AccessKeySecret);
                    stsTokenInfo.setExpiration(data.getData().Expiration);
                    stsTokenInfo.setRegion(data.getData().Region);

                    if (stsResultListener != null) {
                        stsResultListener.onSuccess(stsTokenInfo);
                    }
                    StsInfoManager.getInstance().setStsTokenInfo(stsTokenInfo);
                    // base库赋值
                    StsInfoService.getInstance().setStsTokenInfo(stsTokenInfo);
                } else {
                    if (stsResultListener != null) {
                        stsResultListener.onFail();
                    }
                }
            }

            @Override
            public void onFail(int errCode, String errMsg) {
                if (stsResultListener != null) {
                    stsResultListener.onFail();
                }
            }
        });
    }

    /**
     * 优量汇广告SDK初始化
     *
     * @param context
     */
    private void config(Context context) {
        try {
//            CrashReport.initCrashReport(this, Constants.BuglyAppID, true);

            // 通过调用此方法初始化 SDK。如果需要在多个进程拉取广告，每个进程都需要初始化 SDK。
            GDTADManager.getInstance().initWith(context, "1111174059");

            int channel = Util.getChannel(context, "UMENG_CHANNEL");
            GlobalSetting.setChannel(channel);
            GlobalSetting.setEnableMediationTool(true);
            MultiProcessFlag.setMultiProcess(true);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 多游
     */
    private void initDy(Context context){
        DyAdApi.getDyAdApi().init(context,"dy_59634032", "ffefa9ce8232d87a1c84129ed1bede09");
//        try {
//            // 如果你自己需要用到oaid，就调用下面代码，不用就去掉
//            if (Build.VERSION.SDK_INT >= 29) {
//                MiitHelper miitHelper = new MiitHelper(new MiitHelper.AppIdsUpdater() {
//                    @Override
//                    public void OnIdsAvalid(@NonNull String oaid) {
//                        Log.i("json", "oaid = " + oaid);
//                    }
//                });
//                Log.i("json", "oaid = 获取OAID");
//                miitHelper.getDeviceIds(this);
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }

    @SuppressLint("CheckResult")
    private void observeOaid(Context context){
        Observable.just("")
                .observeOn(Schedulers.io())
                .subscribe(s -> {
                            try{
                                DevicesIDsHelper mDevicesIDsHelper = new DevicesIDsHelper(ids -> {
                                    if (!TextUtils.isEmpty(ids)) {
                                        ShuaApplication.oaid = ids;
                                        //多游oaid
                                        DyAdApi.getDyAdApi().putOAID(context, ShuaApplication.oaid);
                                    }
                                });
                                mDevicesIDsHelper.getOAID(context);
                            }catch (Exception ignored){

                            }
                        }
                );
    }

    /**
     * adMobile
     */
    private void initADSuyi(Context context) {
        String processName = Util.getProcessName(context);
        if (!"com.zf.shuashua".equals(processName)) {
            return;
        }
        // 初始化ADSuyi广告SDK
        ADSuyiSdk.getInstance().init(context, new ADSuyiInitConfig.Builder()
                // 设置APPID
                .appId("3606393")
                // 是否开启Debug，开启会有详细的日志信息打印
                .debug(BuildConfig.ENABLE_DEBUG)
                // 是否同意隐私政策
                .agreePrivacyStrategy(true)
                // 是否过滤第三方平台的问题广告（例如: 已知某个广告平台在某些机型的Banner广告可能存在问题，如果开启过滤，则在该机型将不再去获取该平台的Banner广告）
                .filterThirdQuestion(true)
                // 如果开了浮窗广告，可设置不展示浮窗广告的界面，第一个参数为是否开启默认不展示的页面（例如:激励视频播放页面），第二可变参数为自定义不展示的页面
                .floatingAdBlockList(false, "com.zf.shuashua.SplashActivity")
                .build());
    }

}
